package ltd.dujiabao.ucenterservice.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.commonutils.JwtUtils;
import ltd.dujiabao.commonutils.Result;
import ltd.dujiabao.commonutils.ResultCode;
import ltd.dujiabao.servicebase.exception.MyException;
import ltd.dujiabao.ucenterservice.entity.UcenterMember;
import ltd.dujiabao.ucenterservice.entity.vo.LoginVo;
import ltd.dujiabao.ucenterservice.entity.vo.RegisterVo;
import ltd.dujiabao.ucenterservice.service.UcenterMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author dujiabao
 * @since 2021-04-24
 */
@Api("用户方面的请求，比如登录注册")
@RestController
@RequestMapping("/ucenterservice/member")
@CrossOrigin
@Slf4j
public class UcenterMemberController {
  @Autowired
  UcenterMemberService ucenterMemberService;

  @ApiOperation("用户登录")
  @PostMapping("/login")
  public Result login(@RequestBody LoginVo loginVo) {
    String token = ucenterMemberService.login(loginVo);
    return Result.success().addData("token", token);
  }

  @ApiOperation("用户注册")
  @PostMapping("/register")
  public Result register(@RequestBody RegisterVo registerVo) {
    boolean isSuccess = ucenterMemberService.register(registerVo);
    if (isSuccess) {
      log.info("用户注册成功 : " + registerVo.toString());
      return Result.success();
    } else {
      log.info("用户注册失败 : " + registerVo.toString());
      throw new MyException(ResultCode.FAILURE, "用户注册失败");
    }
  }

  @ApiOperation("用户登录成功的信息获取")
  @GetMapping("/loginInfo")
  public Result getLoginInfo(HttpServletRequest request) {
    String id = JwtUtils.getMemberIdByJwtToken(request);
    UcenterMember member = ucenterMemberService.getById(id);
    log.info("用户信息为 ： " + member.toString());
    return Result.success().addData("data", member);
  }
}

